package com.wenjie.exception;

import com.wenjie.common.unifiedReturn.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author wenjie
 * @Description 异常处理器
 * @date 2024/6/11 9:59
 */
@Slf4j
@RestControllerAdvice
public class AllExceptionHandler {


    /**
     * @Description 传入参数处理
     * @author wenjie
     * @date 2024/6/27 16:40
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result MethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
            log.info(fieldError.getField());
            System.out.println(fieldError.getField());
        }
        ex.printStackTrace();
        return Result.fail("入参校验错误");
    }

    /**
     * @Description 传入参数处理
     * @author wenjie
     * @date 2024/6/27 16:40
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result ConstraintViolationException(ConstraintViolationException ex) {
        ex.printStackTrace();
        return Result.fail("入参校验错误");
    }


    /**
     * @Description 处理一下 数据库处理的时候 触发重复约束
     * @author wenjie
     * @date 2024/6/27 16:30
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public Result duplicateKeyException(DuplicateKeyException ex) {
        ex.printStackTrace();

        // 定义正则表达式匹配模式
        String regex = "Duplicate entry '(.*?)' for key";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(ex.getCause().getMessage());

        // 查找匹配项
        if (matcher.find()) {
            String duplicateEntry = matcher.group(1);
            return Result.fail("\"" + duplicateEntry.substring(0, duplicateEntry.length() - 2) + "\"" + " 字段重复");
        } else {
            return Result.fail(ex.getCause().getMessage());
        }
    }


    /**
     * @Description 登录异常处理
     * @author wenjie
     * @date 2024/6/11 9:57
     */
    @ExceptionHandler(Exception.class)
    public Result exceptin(Exception ex) {
        ex.printStackTrace();
        return Result.fail(ex.getMessage());
    }


    public String getFile(Object obj, String fileName) {
        try {
            Object o = obj.getClass().newInstance();
            Field field = obj.getClass().getField(fileName);
            field.setAccessible(true);
            Object o1 = field.get(obj);
            return String.valueOf(o1);
        } catch (Exception e) {
            return null;
        }
    }

}
